/*
 *
 * Copyright(c) 2018-2019 chj <1019487871@qq.com>
 * QQ: 1019487871
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
#include "los.h"
#include "../component/fundation/list/los_list.h"

int los_list_get_length(struct los_list_t *head)
{
    int length = 0;
    while (head != NULL)
    {
        length++;
        head = head->next;
    }
    return length;
}

struct los_list_t *los_list_get_node(struct los_list_t *head, int idx)
{
    struct los_list_t *node = head;
    int pos = 0;
    while (node != NULL)
    {
        if (pos++ == idx)
            return node;
        node = node->next;
    }
    return node;
}

int los_list_get_idx(struct los_list_t *head, struct los_list_t *node)
{
    int index = 0;
    while (head != NULL)
    {
        if (head == node)
        {
            return index;
        }
        head = head->next;
        index++;
    }
    return -1;
}

int los_list_is_in(struct los_list_t *head, struct los_list_t *node)
{
    return los_list_get_idx(head, node) >= 0;
}

int los_list_remove(struct los_list_t **head, struct los_list_t *node)
{
    if (!djylist_is_in(*head, node))
    {
        return -1;
    }

    if (*head == node)
    {
        *head = node->next;
        return 0;
    }
    while (*head != NULL)
    {
        if ((*head)->next == node)
        {
            (*head)->next = node->next;
            break;
        }
        *head = (*head)->next;
    }
    return 0;
}

void los_list_append(struct los_list_t *head, struct los_list_t *new_node)
{
    struct los_list_t *next;

    next = head;
    while (next->next != NULL)
        next = next->next;

    next->next = new_node;
    new_node->next = NULL;
}

void los_list_delete_next(struct los_list_t *head)
{
    struct los_list_t *next;

    next = head->next;
    if (next->next)
        head->next = next->next;
    else
        head->next = NULL;
}


